package com.javastudy.forum.controller;

import com.javastudy.forum.common.AppResult;
import com.javastudy.forum.common.ResultCode;
import com.javastudy.forum.config.AppConfig;
import com.javastudy.forum.model.Message;
import com.javastudy.forum.model.User;
import com.javastudy.forum.service.IMessageService;
import com.javastudy.forum.service.IUserService;
import com.javastudy.forum.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import sun.dc.pr.PRError;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author Chooker
 * @create 2023-08-24 11:48
 */
@RestController
@RequestMapping("/message")
@Slf4j
@Api(tags = "消息接口")
public class MessageController {
    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @PostMapping("/create")
    @ApiOperation("发送消息")
    public AppResult create(@ApiParam("消息内容") @RequestParam("content") @NonNull String content,
                            @ApiParam("消息接收方") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                            HttpServletRequest httpServletRequest) {
        if (StringUtils.isEmpty(content) || receiveUserId == null) {
            return AppResult.failed("内容和接收者id不能为null");
        }
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        //校验用户是否存在
        if (user == null || user.getDeletestate() == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //校验用户状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发送消息");
        }
        //查询接受者
        User receiveUser = userService.selectById(receiveUserId);
        //校验接受者状态
        if (receiveUser == null || receiveUser.getDeletestate() == 1) {
            return AppResult.failed("接收者状态异常");
        }
        //构建message对象
        Message message = new Message();
        message.setContent(content);
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        messageService.create(message);

        return AppResult.success("发送成功");

    }

    @GetMapping("/getUnreadCount")
    @ApiOperation("获取未读数")
    public AppResult<Long> getUnreadCount(HttpServletRequest httpServletRequest) {
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        //检验用户
        if (user == null || user.getDeletestate() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        Long num = messageService.selectUnreadCount(user.getId());
        return AppResult.success(num);

    }

    @GetMapping("/getAll")
    @ApiOperation("查询用户的所有站内信")
    public AppResult<List<Message>> getAll(HttpServletRequest httpServletRequest) {
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        //检验用户
        if (user == null || user.getDeletestate() == 1 || user.getId() == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);

    }

    @PostMapping("/markRead")
    @ApiOperation("更新为已读")
    public AppResult markRead(HttpServletRequest httpServletRequest,
                              @ApiParam("消息id") @RequestParam("id") Long id) {
        Message message = messageService.selectById(id);
        //校验消息的状态
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        //校验接受者是否和当前用户一致
        if (user.getId() != message.getReceiveUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(id, (byte) 1);
        return AppResult.success("更改状态成功");

    }

    @PostMapping("/reply")
    @ApiOperation("回复站内信")
    public AppResult reply(HttpServletRequest httpServletRequest,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {
        //校验当前用户状态
        HttpSession session = httpServletRequest.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验要回复的站内信状态
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == message.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        //构造对象
        Message postMessage = new Message();
        postMessage.setContent(content);
        postMessage.setUpdateTime(new Date());
        postMessage.setCreateTime(new Date());
        postMessage.setPostUserId(user.getId());
        postMessage.setReceiveUserId(message.getPostUserId());

        messageService.reply(repliedId, postMessage);
        return AppResult.success("回复成功");


    }

}
